/*
 *  Copyright 2016 http://www.kedacomframework.org
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */

package com.kedacom.ctsp.authz.oauth2.service.refresh;

import com.kedacom.ctsp.authority.service.UserService;
import com.kedacom.ctsp.authz.oauth2.OAuth2ServerProperties;
import com.kedacom.ctsp.authz.oauth2.configuration.KeyConfiguration;
import com.kedacom.ctsp.authz.oauth2.core.ErrorType;
import com.kedacom.ctsp.authz.oauth2.core.GrantType;
import com.kedacom.ctsp.authz.oauth2.core.JWTConfigProperties;
import com.kedacom.ctsp.authz.oauth2.entity.AccessToken;
import com.kedacom.ctsp.authz.oauth2.entity.Client;
import com.kedacom.ctsp.authz.oauth2.core.OAuth2Exception;
import com.kedacom.ctsp.authz.oauth2.service.AbstractAuthorizationService;
import com.kedacom.ctsp.authz.oauth2.util.JWTUtil;
import com.kedacom.ctsp.lang.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Set;

/**
 * TODO 完成注释
 *
 * @author
 */
public class DefaultRefreshTokenGranter extends AbstractAuthorizationService implements RefreshTokenGranter {

    @Autowired
    private OAuth2ServerProperties serverProperties;

    @Autowired
    private KeyConfiguration keyConfiguration;

    @Autowired
    private JWTConfigProperties jwtConfigProperties;

    @Autowired
    private UserService userService;

    @Override
    public AccessToken refreshToken(RefreshTokenRequest request) {
        String clientId = request.getClientId();
        String clientSecret = request.getClientSecret();
        String refreshToken = request.getRefreshToken();
        assertParameterNotBlank(clientId, ErrorType.ILLEGAL_CLIENT_ID);
        assertParameterNotBlank(clientSecret, ErrorType.ILLEGAL_CLIENT_SECRET);
        assertParameterNotBlank(refreshToken, ErrorType.ILLEGAL_REFRESH_TOKEN);

        Client client = getClient(clientId, clientSecret);
        assertGrantTypeSupport(client, GrantType.REFRESH_TOKEN);

        AccessToken accessToken = accessTokenService.getTokenByRefreshToken(refreshToken);
        if (accessToken == null) {
            throw new OAuth2Exception(ErrorType.ILLEGAL_REFRESH_TOKEN);
        }
        if (System.currentTimeMillis() - accessToken.getCreateTime() > serverProperties.getRefreshTokenExpireSeconds() * 1000) {
            throw new OAuth2Exception(ErrorType.EXPIRED_REFRESH_TOKEN);
        }
        Set<String> newRange = request.getScope() != null ? request.getScope() : accessToken.getScope();
        if (!accessToken.getScope().containsAll(newRange)) {
            throw new OAuth2Exception(ErrorType.SCOPE_OUT_OF_RANGE);
        }
        accessToken.setAccessToken(accessTokenService.createToken().getAccessToken());
        accessToken.setScope(newRange);
        accessToken.setUpdateTime(System.currentTimeMillis());
        accessTokenService.saveOrUpdateToken(accessToken);

        String jwtToken;
        String username = userService.get(accessToken.getOwnerId()).getUsername();

        if (StringUtils.isEmpty(username) || null == username) {
            throw new OAuth2Exception(ErrorType.ILLEGAL_USERNAME);
        }

        try {
            jwtToken = JWTUtil.generateUserToken(keyConfiguration.getUserPriKey(), username, jwtConfigProperties.getJwtExpire());
        } catch (Exception e) {
            throw new OAuth2Exception(ErrorType.ILLEGAL_JWT_TOKEN);
        }

        accessToken.setJwtToken(jwtToken);
        return accessToken;
    }
}
